package com.vanysoft.framework.exception;

import com.vanysoft.business.sys.util.DictionaryCodeEnum;
import com.vanysoft.common.utils.exception.ExceptionUtil;
import com.vanysoft.framework.aop.VanySoftValidationException;
import com.vanysoft.framework.messagesource.MessageCodeConstant;
import com.vanysoft.framework.utils.BaseResponse;
import com.vanysoft.framework.utils.JSONResponse;
import com.vanysoft.framework.utils.ValidateResponse;
import com.vanysoft.framework.validation.VanySoftValidationErr;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 类名称：BaseExceptionHandler
 * 类描述：vanysoft异常拦截器
 * 创建人：SharpClaw_x
 * 创建时间：2017年5月15日 上午10:21:49
 * 修改人：SharpClaw_x
 * 修改时间：2017年5月15日 上午10:21:49
 * 版本信息：@version 1.0
 * Copyright (c) 2017SharpClaw-版权所有
 * 修改备注：
 */
@ResponseBody
@Order(1)
@ControllerAdvice(basePackages = "com.vanysoft")
public class BaseExceptionHandler {
    private final Log log = LogFactory.getLog(getClass());

    @Resource
    private MessageSource messageSource;

    @ExceptionHandler(VanySoftBaseException.class)
    public BaseResponse methodArgumentNotValidHandler(HttpServletRequest request, VanySoftBaseException e) {
        if (StringUtils.isEmpty(e.getErrCode())) {
            e.setErrCode(MessageCodeConstant.RTN_CODE_UNKNOW_ERROR);
        }
        if (StringUtils.isEmpty(e.getErrMsg())) {
            e.setErrMsg(messageSource.getMessage(e.getErrCode(), null, LocaleContextHolder.getLocale()));
        }
        if (e instanceof VanySoftValidationException) {
            VanySoftValidationException validationExceprtion = (VanySoftValidationException) e;
            StringBuilder errMsg = new StringBuilder();
            for (VanySoftValidationErr err : validationExceprtion.getErrList()) {
                String[] msgs = err.getMessage();
                errMsg.append("  ");//.append(err.getField()).append("【");
                for (String msg : msgs) {
                    if (errMsg.indexOf(msg) == -1) {
                        errMsg.append(msg).append(" ");
                    }
                }
                //errMsg.append("】");
            }

            ValidateResponse validateResponse = new ValidateResponse(errMsg.toString());
            validateResponse.setRspMsg(errMsg.toString());
            return validateResponse;
        }
        String exceptionStackTrace = ExceptionUtil.stackTraceToString(e);
        if (StringUtils.isNotEmpty(e.getErrCode())) {
            log.error(e.getErrCode() + ":" + e.getErrMsg());
        }
        log.error(exceptionStackTrace);
        JSONResponse jsonResponse = new JSONResponse(e.getErrCode(), e.getErrMsg());
        jsonResponse.setDebuggerErrorMsg(exceptionStackTrace);
        return jsonResponse;
    }

//	@ExceptionHandler(VanySoftValidationException.class)
//	public @ResponseBody JSONResponse VanySoftValidationExceprtionHandler(HttpServletRequest request, VanySoftValidationException e)
//			throws Exception {
//
//		VanySoftValidationException validationExceprtion = (VanySoftValidationException) e;
//		
//		JSONResponse jsonResponse = new JSONResponse(validationExceprtion.getErrCode(), validationExceprtion.getErrList());
//		
//		return jsonResponse;
//	}

    @RequestMapping("/error")
    public String welcome() {
        System.err.println("error.html");
        return "error";
    }

    @ModelAttribute(name = "dictionaries")
    public DictionaryCodeEnum[] title() {
        return DictionaryCodeEnum.values();
    }

}
